#include "Socket.hpp"
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket>,InetAddr&)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,ioservice_t service)
    :_port(port)
    ,_listensockptr(std::make_unique<TcpSocket>())
    ,_isrunning(false)
    ,_service(service)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if(sock == nullptr)
                continue;
            LOG(LogLevel::DEBUG) << "accept success...";

            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                _listensockptr->Close();//子进程只需要sock即可
                if(fork() > 0)
                    exit(OK);

                //任务交给孙子进程
                //至于任务是啥？不关该服务器层的事情，只需要外部传递回调函数即可
                _service(sock,client);
                sock->Close();
                exit(OK);
            }
            else
            {
                sock->Close();//父进程只需要_listensockptr
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }

        }
        _isrunning = false;
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;//父类指针
    bool _isrunning;
    ioservice_t _service;
};